import Point from "../point";
import GameBoard from "./gameboard";

export class BallFactory {
  private ballPrefab: cc.Prefab = null;
  private _nodePool: cc.NodePool;
  private pointsBoard: cc.Node;
  private gameBoard: GameBoard;

  constructor() {
  }

  public init(prefab: cc.Prefab, gameboard: GameBoard) {
    this.ballPrefab = prefab;
    this.gameBoard = gameboard;
    this.pointsBoard = gameboard.node.getChildByName('points')
    this.initBalls();
  }

  private initBalls() {
    this._nodePool = new cc.NodePool();
    for (let i = 0; i < 60; i++) {
      const ai = cc.instantiate(this.ballPrefab)
      this._nodePool.put(ai)
    }
  }

  public create(): Point {
    let point = null;
    if (this._nodePool.size() > 0) {
      point = this._nodePool.get();
    } else {
      point = cc.instantiate(this.ballPrefab);
    }
    point.parent = this.pointsBoard;
    const pointScript = point.getComponent(Point)
    pointScript.gameBoard = this;
    pointScript.random();
    pointScript.enabled = true;
    return pointScript;
  }

  public recycle(ball: cc.Node) {
    ball.parent = null;
    this._nodePool.put(ball)
  }
}

export const ballFactory = new BallFactory();